package com.zszedu.web.controller;

import com.zszedu.constants.RedisKeyConstants;
import com.zszedu.pojo.BidInfo;
import com.zszedu.service.BigInfoService;
import com.zszedu.vo.BigInfoVo;
import com.zszedu.web.config.RedisConfig;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("big")
public class BigInfoController {
    @DubboReference
    private BigInfoService bigInfoService;

    @Autowired
    private RedisConfig redisConfig;

    //查询 money 总数
    @GetMapping("totalMoney")
    public Double sumMoney() {
        ValueOperations redis = redisConfig.getRedis();
        Double money = (Double) redis.get(RedisKeyConstants.REDIS_MONEY);
        //为空则Redis中不存在该数据，存入数据
        if (money == null) {
            money = bigInfoService.queryMoney();
            // 存储时间为 1 小数
            redis.set(RedisKeyConstants.REDIS_MONEY,money,1, TimeUnit.HOURS);
        }
        return money;
    }

    //查询投标金额最高的三个用户
    @GetMapping("ranking")
    public List<Map> queryTopMoney(){
        String key = "TOP:ranking";
        ValueOperations redis = redisConfig.getRedis();
        List list = (ArrayList) redis.get(key);

        if (list == null){
            list = bigInfoService.queryTopMoney(3);
            redis.set(key,list);
        }
        return list;
    }

    //查询 用户手机号/投资金额/投资时间
    @GetMapping("records/{id}")
    public List<BigInfoVo> query(@PathVariable Long id){
        List<BigInfoVo> query = bigInfoService.query(id);
        System.out.println(query);
        System.out.println(query);
        System.out.println(query);
        return query;
    }

    //查询最近投资信息，根据用户id查询用户最近的投资信息以及投资产品名称
    @GetMapping("recentRec")
    public List<BidInfo> recentRec(@RequestHeader("uid") Long uid){
        return bigInfoService.queryRecentInvest(uid);
    }

    //投资
    @PostMapping("bid/{pid}/{money}")
    public Map bid(@PathVariable Integer pid,
                   @PathVariable Double money,
                   @RequestHeader("uid") Long uid){
        bigInfoService.Invest(uid, pid, money);
        return new HashMap(){{
            put("success",true);
        }};
    }


}
